import 'package:api/pages/provider/provider/home_item_page.dart';
import 'package:api/pages/provider/provider/model/home_card_model.dart';
import 'package:api/pages/provider/provider/model/home_tab_model.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

class ProviderHomePage extends StatefulWidget {
  @override
  _ProviderHomePageState createState() => _ProviderHomePageState();
}

class _ProviderHomePageState extends State<ProviderHomePage>
    with TickerProviderStateMixin {
  TabController _tabController;
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    Future.delayed(Duration(milliseconds: 2000), () {
      context.read<HomeTabModel>().request();
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Color(0xfff6f6f6),
      appBar: AppBar(
        title: Text("provider学习"),
        bottom: buildTabs(),
      ),
      body: buildTabView(),
      floatingActionButton: Stack(alignment: Alignment.center, children: [
        ClipOval(
          child: Container(
            color: Colors.orange,
            height: 44,
            width: 44,
          ),
        ),
        Positioned(
          child: Text("${context.watch<HomeCardModel>().cardList.length}",
              style: TextStyle(color: Colors.white)),
        ),
      ]),
    );
  }

  // 构建tabbar
  buildTabs() {
    List<TabBean> list = context.watch<HomeTabModel>().tabList;
    if (list.length == 0) {
      return PreferredSize(
        child: Container(
            margin: EdgeInsets.only(bottom: 12),
            alignment: Alignment.center,
            child: Text("加载中...", style: TextStyle(color: Colors.white))),
        preferredSize: Size(MediaQuery.of(context).size.width, 40),
      );
    }
    List<Tab> tabList = [];
    list.forEach((v) {
      tabList.add(
        Tab(text: v.title),
      );
    });
    _tabController = new TabController(length: tabList.length, vsync: this);
    return TabBar(
      isScrollable: true,
      controller: _tabController,
      tabs: tabList,
    );
  }

  buildTabView() {
    if (_tabController == null) {
      return Center(
        child: Text("加载中..."),
      );
    }
    List<TabBean> list = context.watch<HomeTabModel>().tabList;
    List<HomeItemPage> itemList = [];
    list.forEach((item) {
      itemList.add(HomeItemPage(tabBean: item));
    });
    return TabBarView(controller: _tabController, children: itemList);
  }
}
